﻿/*
 * GET landing page.
 */

exports.redirect = function(req, res) {
	res.redirect('/');
}

exports.password = function(req, res) {
	res.render('password');
}

exports.passwordReset = function(req, res) {
	var data = req.body.reset;
	var mysql = require('mysql')
	,	db = '';
	
	var connection = mysql.createConnection({
		host: '',
		port: '',
		user: '',
		password: '',
	});

	connection.connect(function(err) {
		if (err) throw err;
	});
	
	connection.query('use ' + db);
	console.log(data.email);
	connection.query("select * from users where email='" + data.email + "'", function(err, result, fields) {
		if (err) res.render('error', {errori:err});
		else {
			if (result.length == 1) {
				var crypto = require('crypto')
				,	shasum = crypto.createHash('sha1')
				,	randombit = Math.floor(Math.random()*100+1)*Math.floor(Math.random()*100+1);
					shasum.update(data.username + 'salt' + randombit);
				var token = shasum.digest('hex');
				
				var email = require("emailjs");
				var server = email.server.connect({
				   user: "", 
				   password: "", 
				   host: "", 
				   ssl: true

				});
				
				// send the message and get a callback with an error or details of the message that was sent
				server.send({
				   text: "Click the following link to reset your password: yourdomain.com/recovery/" + token, 
				   from: "", 
				   to: "<" + data.email + ">",
				   subject: "Password reset link"
				}, function(err, message) {
					var mysql = require('mysql')
					,	db = '';
					
					var connection = mysql.createConnection({
						host: '',
						port: '',
						user: '',
						password: '',
					});

					connection.connect(function(err) {
						if (err) res.render('error', {error:err});
					});
					
					connection.query('use ' + db);
					var thisdate = new Date().getTime() + 1000*3600;
					connection.query("insert into auth(`user`, `date`, `token`) values ('" + result[0].username + "', '" + thisdate + "', '" + token + "')", function(err, info) {
						if (err) {
							console.log(err);
							var s = err.toString();
							var e = s.split(' ');
							e = e[7].split("'");
							s = s.split(':');
							if (s[1] == ' ER_DUP_ENTRY') var errori = 'Sorry, but that ' + e[1] + ' is already taken';
							else var errori = err;
							res.render('error', {errori:errori});
						}
					});
					
					connection.end();
					console.log(err); 
					res.redirect('/');
				});
			} else {
				res.render('password', {errori:'email wrong'});
			}
		}
	});
	
	connection.end();
}
 
exports.recoveryPost = function(req, res) {
	var done = false;
	var data = req.body.recovery;
	var crypto = require('crypto')
	,	shasum = crypto.createHash('sha1');
		shasum.update(data.password + 'salt');
	var passu = shasum.digest('hex');
	
	var mysql = require('mysql')
	,	db = '';
	
	var connection = mysql.createConnection({
		host: '',
		port: '',
		user: '',
		password: '',
	});

	connection.connect(function(err) {
		if (err) throw err;
	});
	
	connection.query('use ' + db);

	connection.query("select * from auth where token='" + data.token + "'", function(err, result, fields) {
		if (err) res.render('error', {errori:err});
			var user = result[0].user;
			if (typeof(user) != 'undefined') {
				connection.query("update users set `password`='" + passu + "' where `username`='" + user + "'", function(err2, info) {
					if (err2) res.render('error', {errori:err2});
					var done = true;
					res.redirect('/');
				});
			}
	});
	if (done) connection.end();
}
 
exports.recovery = function(req, res) {
	var token = req.params.token;
	var mysql = require('mysql')
	,	db = '';
	
	var connection = mysql.createConnection({
		host: '',
		port: '',
		user: '',
		password: '',
	});

	connection.connect(function(err) {
		if (err) throw err;
	});
	
	connection.query('use ' + db);

	connection.query("select * from auth where token='" + token + "'", function(err, result, fields) {
		if (err) res.render('error', {errori:err});
		else {
			if (result.length == 1) {
				var postdate = result[0].date*1.0;
				currentdate = new Date().getTime();
				if (postdate < currentdate) {
					console.log('Over an hour since reset request');
					res.render('error', {errori:'Over an hour since you requested password reset. Token is too old'});
				} else {
					res.render('recovery', {token : token});			
				}
			} else {
				res.redirect('/');
			}
		}
	});
	
	connection.end();
}

 
exports.login = function(req, res) {
	var data = req.body.login;
	var crypto = require('crypto')
	,	shasum = crypto.createHash('sha1');
		shasum.update(data.password + 'salt');
	var passu = shasum.digest('hex');
	
	var mysql = require('mysql')
	,	db = '';
	
	var connection = mysql.createConnection({
		host: '',
		port: '',
		user: '',
		password: '',
	});

	connection.connect(function(err) {
		if (err) throw err;
	});
	
	connection.query('use ' + db);

	connection.query("select * from users where username='" + data.username + "' and password='" + passu + "'", function(err, result, fields) {
		if (err) res.render('error', {error:err});
		else {
			if (result.length == 1) {
				console.log('log in successful');
				req.session.logged = data.username;
				res.redirect('/');
			} else {
				res.render('index', {errori: 'Wrong Username or Password'});
			}
		}
	});
	
	connection.end();
}

exports.logout = function(req, res) {
	req.session.logged = null;
	res.redirect('/');
}

exports.register = function(req, res) {
	var data = req.body.register;
	var crypto = require('crypto')
	,	shasum = crypto.createHash('sha1');
		shasum.update(data.password + 'salt');
	var passu = shasum.digest('hex');
	
	var mysql = require('mysql')
	,	db = '';
	
	var connection = mysql.createConnection({
		host: '',
		port: '',
		user: '',
		password: '',
	});

	connection.connect(function(err) {
		if (err) res.render('error', {error:err});
	});
	
	connection.query('use ' + db);

	connection.query("insert into users(`username`, `password`, `email`) values ('" + data.username + "', '" + passu + "', '" + data.email + "')", function(err, info) {
		if (err) {
			console.log(err);
			var s = err.toString();
			var e = s.split(' ');
			e = e[7].split("'");
			s = s.split(':');
			if (s[1] == ' ER_DUP_ENTRY') var errori = 'Sorry, but that ' + e[1] + ' is already taken';
			else var errori = err;
			res.render('index', {errory:errori});
		}
		else res.redirect('/');
	});
	
	connection.end();

}
 
exports.index = function(req, res) {
	if (typeof(req.session.logged) != 'undefined' && req.session.logged != null) res.render('index', {data:"'"+req.session.logged+"'"});
	else res.render('index');
};